import React, { Component } from "react";
import {
  Button,
  Table,
  DatePicker,
  Badge,
  Form,
  Row,
  Col,
  Input,
  message,
  Modal
} from "antd";
import moment from "moment";
import { connect } from "dva";
import tableFilter from "../../../../../components/tableFilter";
import styles from "./index.less";
import api from "../../../services/addMessageApi";

const { RangePicker } = DatePicker;

@connect(stores => ({
  messageData: stores.channelModel
}))
@tableFilter
@Form.create()
class MessageSource extends Component {
  state = {
    pageNum: 1,
    pageSize: 10,
    loading: false,
    listOfLog: [],
    listTotal: 0,
    visible: false,
    msgContent: ""
  };

  componentDidMount() {
    this.initData();
    this.filterFun();
  }

  initData = () => {
    const { location } = this.props;
    // const data = JSON.parse(sessionStorage.getItem("msgSourceRecord"));
    let data = location.search.split("=");
    if (data[1]) {
      data = JSON.parse(decodeURIComponent(data[1]));
    } else {
      // data = JSON.parse(JSON.stringify(msgSourceRecord));
      message.warning("无数据，请返回列表重新操作");
      return;
    }
    this.props.form.setFieldsValue({
      sceneName: data.sceneName,
      sourceName: data.sourceName,
      rangeTime: [moment().subtract(7, "days"), moment()]
    });
  };

  renderState = (status, text) => {
    if (status === 1) {
      return <Badge status="success" text={text} />;
    }
    if (status === -1) {
      return <Badge status="error" text={text} />;
    }
    if (status === 2) {
      return <Badge status="default" text={text} />;
    }
    return <Badge status="warning" text={text} />;
  };

  handleTableChange = e => {
    const { current, pageSize } = e;
    this.setState(
      {
        pageSize,
        pageNum: current
      },
      () => {
        this.filterFun();
      }
    );
  };

  clearChange = e => {
    if (e.target.value !== "") return;
    this.setState(
      {
        pageNum: 1
      },
      () => {
        this.filterFun();
      }
    );
  };

  filterFun = () => {
    const { pageSize, pageNum } = this.state;
    const { form, location } = this.props;
    // const data = JSON.parse(sessionStorage.getItem("msgSourceRecord"));
    let data = location.search.split("=");
    if (data[1]) {
      data = JSON.parse(decodeURIComponent(data[1]));
    } else {
      // data = JSON.parse(JSON.stringify(msgSourceRecord));
      message.warning("无数据，请返回列表重新操作");
      return;
    }
    const beginTime =
      form.getFieldValue("rangeTime").length === 2
        ? moment(form.getFieldValue("rangeTime")[0]).set({
            hour: 0,
            minute: 0,
            second: 0
          })
        : "";
    const endTime =
      form.getFieldValue("rangeTime").length === 2
        ? moment(form.getFieldValue("rangeTime")[1]).set({
            hour: 23,
            minute: 59,
            second: 59
          })
        : "";
    const params = {
      pageNum,
      pageSize,
      sceneCode: data.sceneCode,
      sourceCode: data.sourceCode,
      beginTime,
      endTime
    };
    this.setState({ loading: true });
    api.msgQueryLog(params).then(res => {
      if (res.success) {
        this.setState({
          listOfLog: res.datas || [],
          listTotal: res.totalCount
        });
      } else {
        message.error(res.errMsg);
      }
      this.setState({ loading: false });
    });
  };

  onReset() {
    const { form } = this.props;
    form.setFieldsValue({
      rangeTime: [moment().subtract(7, "days"), moment()]
    });
  }

  handleSubmit() {
    this.filterFun();
  }

  lookContent(text) {
    this.setState({
      visible: true,
      msgContent: text
    });
  }

  render() {
    const { form } = this.props;
    const {
      pageNum,
      pageSize,
      loading,
      listOfLog = [],
      listTotal = 0,
      visible,
      msgContent
    } = this.state;
    const { getFieldDecorator } = form;
    const columns = [
      {
        title: "消息来源",
        ellipsis: true,
        dataIndex: "msgSourceName"
      },
      {
        title: "发送时间",
        ellipsis: true,
        dataIndex: "timeUpdate",
        render: text => moment(text).format("YYYY-MM-DD HH:mm:ss")
      },
      {
        title: "消息内容",
        dataIndex: "content",
        render: text => <a onClick={() => this.lookContent(text)}>查看</a>
      }
    ];
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    };
    return (
      <div className={styles.root}>
        <div className={styles.titleBox}>消息源日志列表</div>
        <div style={{ padding: "24px" }}>
          <div
            style={{
              fontSize: 14,
              color: "rgba(0,0,0,0.85)",
              marginBottom: 16,
              display: "flex",
              alignItems: "center",
              padding: "14px 16px",
              background: "#fff"
            }}
          >
            <Form
              {...formItemLayout}
              onSubmit={() => this.handleSubmit()}
              style={{ width: "100%" }}
            >
              <Row>
                <Col span={6}>
                  <Form.Item label="消息源名称">
                    {getFieldDecorator("sourceName")(
                      <Input disabled placeholder="请输入消息源编码或名称" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="场景名称">
                    {getFieldDecorator("sceneName")(
                      <Input disabled placeholder="请输入场景编码或名称" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="时间范围">
                    {getFieldDecorator("rangeTime")(<RangePicker />)}
                  </Form.Item>
                </Col>
                <Col span={6} style={{ textAlign: "right" }}>
                  <Button
                    style={{ marginRight: "10px" }}
                    onClick={() => this.onReset()}
                  >
                    重置
                  </Button>
                  <Button
                    type="primary"
                    // htmlType="submit"
                    onClick={() => this.handleSubmit()}
                  >
                    搜索
                  </Button>
                </Col>
              </Row>
            </Form>
          </div>
          <Table
            style={{ background: "#fff" }}
            columns={columns}
            size="middle"
            dataSource={listOfLog}
            loading={loading}
            locale={{ emptyText: "暂无数据！" }}
            scroll={
              listOfLog.length === 0 ? { x: false } : { x: "max-content" }
            }
            rowKey="msgId"
            onChange={(e, filters, sorter) =>
              this.handleTableChange(e, filters, sorter)
            }
            pagination={{
              defaultPageSize: 10,
              showQuickJumper: true,
              showSizeChanger: true,
              current: pageNum,
              total: listTotal,
              pageSize,
              showTotal: total => `共有 ${total} 条`
            }}
          />
        </div>
        <Modal
          visible={visible}
          title="消息内容"
          onCancel={() => this.setState({ visible: false })}
          footer={[
            <Button
              key="back"
              onClick={() => this.setState({ visible: false })}
            >
              返回
            </Button>
          ]}
        >
          {msgContent}
        </Modal>
      </div>
    );
  }
}

export default MessageSource;
